package ua.maxicash.service;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailParseException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service("mailService")
public class MailServiceImpl implements MailService {

    private static final Logger logger = Logger.getLogger(MailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    @Override
    @Async
    public void sendMail(String from, String to, String subject, String msg) {

        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(msg,true);

        } catch (MessagingException e) {
            logger.error(e);
            throw new MailParseException(e);
        }
        try {
            mailSender.send(message);
            logger.info("Message : " + message + "has been sent to " + to);
        } catch (Throwable t) {
            logger.fatal(t);
        }


    }

    @Override
    public void sendMailWithFile(String from, String to, String subject, String msg, File file) throws MessagingException {

        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(msg);
            helper.addAttachment("results.png", file);


        } catch (MessagingException e) {
            logger.error(e);
            throw new MailParseException(e);
        }
        try {
            mailSender.send(message);
            logger.info("Message : " + message + "has been sent to " + to);
        } catch (Throwable t) {
            logger.fatal(t);
        }
    }

}
